import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:recipe/detail.dart';
import 'package:recipe/global.dart';
import 'package:recipe/http-manager.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List recipeDateList = [];
  ScrollController _listController = ScrollController();
  bool listLoading = false;
  int page = 2;
  @override
  void initState() {
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.instance.maskType = EasyLoadingMaskType.black;
    _listController.addListener(() {
      if (_listController.position.pixels >=
          _listController.position.maxScrollExtent) {
        if (page > 200) {
          EasyLoading.showToast('没有更多了...');
          return;
        }
        if (!listLoading) {
          setState(() => {listLoading = true});
          EasyLoading.show(status: '正在加载更多菜式...');
          recipeList(page).then((res) {
            setState(() {
              recipeDateList.addAll(res);
              listLoading = false;
              EasyLoading.dismiss();
              page++;
            });
          });
        }
      }
    });

    recipeList(1).then((res) {
      setState(() {
        recipeDateList = res;
        listLoading = false;
      });
    });
    super.initState();
  }

  recipeList(int page) async {
    String url = "recipe/";
    if (page != 1)
      url = "recipe/?" + "limit=20" + "&offset=" + (20 * (page - 1)).toString();
    try {
      var response = await HttpUtils.request(url, method: HttpUtils.GET);
      return response['results'];
    } catch (e) {
      print(e);
    }
  }

  List<Widget> renderRecipeList(recipeDateList) {
    List<Widget> list = [];
    List.generate(recipeDateList.length, (index) {
      String str = json.encode(recipeDateList[index]);
      final item = json.decode(str);
      list.add(
        InkWell(
            onTap: () {
              Navigator.push(
                context,
                MaterialPageRoute(
                  builder: (context) => DetailPage(
                      id: item['recipeId'].toString(), cover: item['cover']),
                ),
              );
            },
            child: Container(
              decoration: BoxDecoration(color: Global.cardBackgroundColor),
              padding: EdgeInsets.all(8),
              width: MediaQuery.of(context).size.width / 4,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Container(
                      child: ClipRRect(
                    borderRadius: BorderRadius.all(Radius.circular(5)),
                    child: FadeInImage.assetNetwork(
                      placeholder: 'assets/images/20201014150850.jpg',
                      fadeInDuration: const Duration(milliseconds: 500),
                      image: item['cover'],
                    ),
                  )),
                  Text(
                    item['title'],
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Global.primaryColor,
                      fontSize: 13,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  Text(
                    item['message'],
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: Global.fontSecondColor,
                      fontSize: 11,
                    ),
                  ),
                ],
              ),
            )),
      );
    });
    return list;
  }

  @override
  Widget build(BuildContext context) {
    return recipeDateList.length == 0
        ? Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 20),
              Text(
                "正在加载热门菜式",
                style: TextStyle(color: Global.fontSecondColor),
              )
            ],
          )
        : Scaffold(
            appBar: AppBar(
              toolbarHeight: 50,
              elevation: 0,
              title: Text(
                "热门菜式",
                style: TextStyle(
                  color: Global.backgroundColor,
                  fontSize: 13,
                ),
              ),
            ),
            body: Container(
              child: SingleChildScrollView(
                controller: _listController,
                child: Wrap(
                  children: renderRecipeList(recipeDateList),
                ),
              ),
            ),
          );
  }
}
